<template>
    <div class="min-h-screen bg-gray-100 p-4 flex flex-col">
        <!-- 上半部分 -->
        <div class="h-[50dvh] flex flex-col md:flex-row gap-4 mb-4">
            <div class="w-full md:w-1/2 bg-white p-4 shadow-lg rounded-lg">
                <var-loading description="LOADING" color="#006263" :loading="loading">
                    <h2 class="text-lg font-semibold mb-2">血涂片图像</h2>
                    <div v-if="!selectImg.path" class="h-[30vh] flex items-center justify-center text-gray-400">暂无血涂片图像</div>
                    <div v-else class="h-[40vh] flex items-center justify-center cursor-pointer">
                        <img :src="selectImg.path" class="max-w-full max-h-full object-contain rounded-lg hover:shadow-lg transition-all" @click="showZoomedImage = true" />
                    </div>
                </var-loading>
            </div>
            <div class="w-full md:w-1/2 flex flex-col md:flex-row gap-2">
                <div class="w-full h-[50dvh] space-y-2">
                    <div class="w-full h-[60%] bg-white p-4 shadow-lg rounded-lg">
                        <h2 class="text-lg font-semibold mb-2">当前图像</h2>
                        <div class="space-y-1 px-4">
                            <var-button type="primary" text outline block @click="selectOriginalImg" :style="{ color: selectImg.type == '原始图像' ? '#006263' : 'rgb(57, 123, 254)' }">原始图像</var-button>
                            <var-button v-for="detail in imgList.details" :key="detail.type" type="primary" text outline block @click="select(detail)" :style="{ color: detail.type === selectImg.type ? '#006263' : 'rgb(57, 123, 254)' }">
                                {{ detail.type }}
                            </var-button>
                        </div>
                    </div>
                    <div class="w-full h-[38%] bg-white p-2 shadow-lg rounded-lg">
                        <h2 class="text-lg font-semibold mb-1">当前图像细胞信息</h2>
                        <div class="space-y-2 px-2">
                            <p>细胞类型：{{ selectImg.type }}</p>
                            <p>细胞数量：{{ selectImg.quantity }}</p>
                            <p>细胞占比：{{ setPercentage(selectImg.percentage) }}</p>
                        </div>
                    </div>
                </div>
                <div class="w-full bg-white p-2 shadow-lg rounded-lg">
                    <h2 class="text-lg font-semibold mb-2">本次检测细胞信息</h2>
                    <div class="space-y-1">
                        <var-select placeholder="当前显示图片" focus-color="#006263" v-model="currentImgSet">
                            <var-option v-for="(set, index) in imgDetail" :key="index" :label="`图片 ${index + 1}`" :value="index" />
                        </var-select>
                        <p>细胞总数:{{ imgList.total }}</p>
                        <div v-for="detail in imgList.details" class="border-2 p-1 text-sm border-[#006263] rounded-lg">
                            <p>细胞类型:{{ detail.type }}</p>
                            <p>细胞数量:{{ detail.quantity }}</p>
                            <p>细胞占比:{{ setPercentage(detail.percentage) }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 下半部分 -->
        <div class="h-[42dvh] flex flex-col md:flex-row gap-4">
            <div class="h-full w-full md:w-1/5 bg-white p-4 shadow-lg rounded-lg">
                <h2 class="text-lg font-semibold mb-2">血常规指标 {{ formatDate(showBloodRoutineIndicator.createdAt) }}</h2>
                <div class="space-y-2">
                    <div v-for="(value, key) in filteredBloodRoutineIndicator" :key="key">
                        <div @click="changeChart(key)">
                            <span class="text-gray-600">{{ key }}:</span>
                            <span class="text-gray-800 font-medium">{{ formatValue(key, value) }}</span>
                        </div>
                    </div>
                    <div class="flex justify-center items-center">
                        <var-icon name="chevron-left" :size="25" @click="prevRecord" />
                        <var-icon name="chevron-right" :size="25" @click="nextRecord" />
                    </div>
                </div>
            </div>
            <div class="w-full md:w-3/5 flex flex-col md:flex-row gap-4">
                <div class="w-full md:w-1/2 bg-white p-4 shadow-lg rounded-lg">
                    <div id="chart1" class="h-[40vh] w-full"></div>
                </div>
                <div class="w-full md:w-1/2 bg-white p-4 shadow-lg rounded-lg">
                    <div id="chart2" class="h-[40vh] w-full"></div>
                </div>
            </div>
            <div class="md:w-1/5 space-y-2">
                <div class="bg-white p-4 shadow-lg rounded-lg" v-if="record">
                    <div class="flex justify-between items-center mb-2">
                        <h2 class="text-lg font-semibold">病人信息</h2>
                        <var-button color="#006263" text-color="white" size="small"  @click="getRecord">查看历史就诊记录</var-button>
                    </div>
                    <div class="space-y-2">
                        <div class="flex">
                            <span class="text-gray-600">姓名:</span>
                            <span class="text-gray-800 font-medium">{{ record.name }}</span>
                        </div>
                        <div>
                            <span class="text-gray-600">就诊卡号:</span>
                            <span class="text-gray-800 font-medium">{{ record.visitCardId }}</span>
                        </div>
                        <div>
                            <span class="text-gray-600">手机号:</span>
                            <span class="text-gray-800 font-medium">{{ record.phone }}</span>
                        </div>
                    </div>
                </div>
                <var-button type="warning" v-if="!record.isUpdate" size="large" @click="showDialog = true" block>撤销该记录</var-button>
                <var-button type="primary" size="large" v-if="ptf.length === 0" :loading="pdfLoading" @click="showOutPutPdf = true" block>生成报告</var-button>
                <var-button type="primary" size="large" v-else @click="openReport(ptf)" block>查看报告</var-button>
                <var-button type="success" size="large" :loading="saveLoading" v-if="!record.isUpdate" @click="save" block>保存结果</var-button>
                <var-button type="success" size="large" v-else @click="newRecord" block>创建新记录</var-button>
            </div>
        </div>
    </div>
    <var-popup v-model:show="showOutPutPdf" class="rounded-xl">
        <var-loading description="LOADING" color="#006263" :loading="pdfLoading">
            <div class="h-[50vh] w-[40vw] p-[1%] flex flex-col items-center justify-center">
                <var-input class="w-[90%]" focus-color="#006263" placeholder="请输入备注" variant="outlined" textarea rows="10" v-model="text" />
                <button class="w-[60%] bg-[#006263] text-white rounded-lg py-2 mt-[3%]" @click="outPutPdf">生成报告</button>
            </div>
        </var-loading>
    </var-popup>
    <var-popup v-model:show="showRecordPopup" class="w-[25vw] h-[42vh] rounded-lg p-2">
        <div class=" max-h-[288px] flex justify-center items-center overflow-auto relative">
            <table class="min-w-full">
                <thead>
                    <tr>
                        <th class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">就诊记录</th>
                        <th class="sticky top-0 bg-gray-50 px-6 py-3 text-center text-base font-medium text-gray-500 z-10">查看</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="recordList.length === 0">
                        <td colspan="2" class="px-6 py-1.4 text-center text-base text-gray-500">暂无数据</td>
                    </tr>
                    <tr v-for="(record, index) in recordList" :key="index" class="odd:bg-white even:bg-gray-50" v-hover="{ color: 'var(--color-on-primary)', background: '#F0F0F0' }">
                        <td class="px-6 py-1.5 text-center text-base text-gray-900">{{ format(record.createdAt) }}</td>
                        <td class="px-6 py-1.5 text-base">
                            <div class="flex flex-col items-center justify-center">
                                <var-space :size="[10, 10]">
                                    <var-button block color="#006263" text-color="white" @click="getRecordDetails(record.recordId)" style="border-radius: 8px">查看</var-button>
                                </var-space>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </var-popup>
    <!-- 撤销弹窗 -->
    <var-dialog title="撤销记录" message="是否撤销该记录？" confirm-button-text-color="#006263" persistent cancel-button-text-color="#006263" @confirm="outRecord" v-model:show="showDialog" />
    <var-popup v-model:show="showZoomedImage" @closed="resetZoom" style="background-color: transparent">
        <div class="h-[80vh] overflow-hidden" @wheel.prevent="handleWheel">
            <div class="w-full h-full flex items-center justify-center" @mousedown="startDrag" @mousemove="doDrag" @mouseup="endDrag" @mouseleave="endDrag">
                <img
                    :src="selectImg.path"
                    :style="{
                        transform: `scale(${scale}) translate(${position.x}px, ${position.y}px)`,
                        transition: isDragging ? 'none' : 'transform 0.3s',
                        cursor: isDragging ? 'grabbing' : 'grab'
                    }"
                    class="max-w-full max-h-full object-contain origin-center"
                    @click.stop
                    @dragstart.prevent />
            </div>
        </div>
    </var-popup>
</template>

<script>
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import { generateReportTemplate, generatePDF } from '../pdf/pdf';
export default {
    data() {
        return {
            bloodRoutineIndicators: [],
            showBloodRoutineIndicator: {},
            imgDetail: [],
            recordList: [],
            showRecordPopup: false,
            saveLoading: false,
            saveRecord: false,
            text: '',
            pdfLoading: false,
            showOutPutPdf: false,
            currentImgSet: 0,
            loading: false,
            selectImg: {
                path: '',
                percentage: '',
                quantity: '',
                type: ''
            },
            ptf: [],
            imgList: {},
            showDialog: false,
            chart1: null,
            chart2: null,
            showZoomedImage: false,
            probability: {},
            currentChartIndex: 0,
            chartOptions: [],
            scale: 1,
            position: { x: 0, y: 0 },
            isDragging: false,
            startPos: { x: 0, y: 0 }
        };
    },
    watch: {
        // 添加监听器处理图片集切换
        currentImgSet(newVal) {
            this.loading = true;
            this.imgList = this.imgDetail[newVal];
            // 默认显示原始图像
            if (this.imgList) {
                this.selectImg = {
                    path: this.imgList.originalImageUrl,
                    type: '原始图像',
                    quantity: this.imgList.total,
                    percentage: '1'
                };
                setTimeout(() => {
                    this.loading = false;
                }, 500);
            }
        }
    },
    computed: {
        record() {
            return this.$store.record;
        },
        user() {
            return this.$store.user;
        },
        filteredBloodRoutineIndicator() {
            const indicators = {};
            for (const [key, value] of Object.entries(this.showBloodRoutineIndicator)) {
                if (key !== 'recordId' && key !== 'patientId' && key !== 'createdAt') {
                    indicators[key] = value;
                }
            }
            return indicators;
        }
    },
    mounted() {
        this.bloodRoutineIndicators = this.record.bloodDrooping.history;
        this.showBloodRoutineIndicator = this.bloodRoutineIndicators[this.bloodRoutineIndicators.length - 1];
        this.probability = this.record.probability;
        this.imgDetail = this.record.imgDetail;
        this.imgList = this.imgDetail[this.currentImgSet];
        if (this.imgList) {
            this.selectImg.path = this.imgList.originalImageUrl;
            this.selectImg.quantity = this.imgList.total;
            this.selectImg.percentage = '1';
            this.selectImg.type = '原始图像';
        }
        this.initCharts();
        this.initChart2();
        this.loading = true;
        setTimeout(() => {
            this.loading = false;
        }, 1000);
    },
    beforeUnmount() {
        if (this.chart1) this.chart1.dispose();
        if (this.chart2) this.chart2.dispose();
    },
    methods: {
        format(date) {
            return dayjs(date).format('YYYY-MM-DD-HH-mm-ss');
        },
        openReport(url) {
            window.open(url, '_blank');
        },
        formatDate(date) {
            return dayjs(date).format('YYYY-MM-DD');
        },
        formatDateList(date) {
            return dayjs(date).format('MM-DD');
        },
        setPercentage(data) {
            return `${(data * 100).toFixed(3)}%`;
        },
        async outPutPdf() {
            this.pdfLoading = true;
            this.$store.record.text = this.text;
            const date = dayjs().format('YYYY-MM-DD');
            try {
                // 生成报告模板
                const template = generateReportTemplate({
                    record: this.record,
                    user: this.user,
                    bloodData: this.filteredBloodRoutineIndicator,
                    probability: this.probability,
                    imgData: this.record.imgDetail,
                    text: this.$store.record.text,
                    date: date
                });
                // 生成PDF
                this.ptf = await generatePDF(template, this.record.name);
                this.$store.record.pdf = this.ptf;
                this.$api.notify.success('文件生成成功');
            } catch (error) {
                console.error(error);
                this.$api.notify.error('文件生成失败');
            } finally {
                this.pdfLoading = false;
                this.showOutPutPdf = false;
            }
        },
        selectOriginalImg() {
            this.loading = true;
            this.selectImg = {
                path: this.imgList.originalImageUrl,
                type: '原始图像',
                quantity: this.imgList.total,
                percentage: '1'
            };
            setTimeout(() => {
                this.loading = false;
            }, 500);
        },
        handleWheel(e) {
            e.preventDefault();
            const delta = e.deltaY > 0 ? 0.9 : 1.1;
            this.scale = Math.min(Math.max(this.scale * delta, 0.5), 5);
        },
        startDrag(e) {
            this.isDragging = true;
            this.startPos = {
                x: e.clientX - this.position.x,
                y: e.clientY - this.position.y
            };
        },
        doDrag(e) {
            if (!this.isDragging) return;
            this.position = {
                x: e.clientX - this.startPos.x,
                y: e.clientY - this.startPos.y
            };
        },
        endDrag() {
            this.isDragging = false;
        },
        resetZoom() {
            this.scale = 1;
            this.position = { x: 0, y: 0 };
        },
        formatValue(key, value) {
            if (key === 'RBC') return `${value} T/L`;
            if (key === 'HGB') return `${value} g/L`;
            if (key === 'HCT') return `${(value * 100).toFixed(1)}%`;
            if (key === 'MCH') return `${value} pg`;
            if (key === 'MCHC') return `${value} g/L`;
            if (key === 'MCV') return `${value} fL`;
            if (key === 'RDW-SD') return `${value} fL`;
        },
        select(detail) {
            this.loading = true;
            this.selectImg = {
                path: detail.imgPath,
                type: detail.type,
                quantity: detail.quantity,
                percentage: detail.percentage
            };
            setTimeout(() => {
                this.loading = false;
            }, 500);
        },
        async getRecord() {
            const res = await this.$api.record.getRecordHistory({ patientId: this.record.patientId });
            if (res.success) {
                this.recordList = res.data;
                this.showRecordPopup = true;
            } else {
                this.$api.notify.error(res.error);
            }
        },
        async getRecordDetails(recordId) {
        this.$router.push({ name: 'recordDetails', params:{ recordId } });
        },
        getChartOptions() {
            const keys = Object.keys(this.showBloodRoutineIndicator).filter((key) => key !== 'recordId' && key !== 'patientId');
            return keys.map((key) => {
                const getUnit = (key) => {
                    if (key === 'RBC') return 'T/L';
                    if (key === 'HGB') return 'g/L';
                    if (key === 'HCT') return '%';
                    if (key === 'MCH') return 'pg';
                    if (key === 'MCHC') return 'g/L';
                    if (key === 'MCV') return 'fL';
                    if (key === 'RDW-SD') return 'fL';
                    return '';
                };
                return {
                    title: {
                        text: `${key}(${getUnit(key)})`,
                    },
                    xAxis: {
                        type: 'category',
                        data: this.bloodRoutineIndicators.slice(-5).map((item) => this.formatDateList(item.createdAt))
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            data: this.bloodRoutineIndicators.map((item) => parseFloat(item[key])),
                            type: 'bar',
                            itemStyle: {
                                color: '#006263' // 新增颜色配置
                            }
                        }
                    ]
                };
            });
        },
        updateChart() {
            if (this.chartOptions.length === 0) return;
            const option = this.chartOptions[this.currentChartIndex];
            this.chart1.setOption(option);
        },
        changeChart(key) {
            const index = Object.keys(this.showBloodRoutineIndicator).findIndex((k) => k === key) - 2;
            if (index !== -1) {
                this.currentChartIndex = index;
                this.updateChart();
            }
        },
        prevRecord() {
            const index = this.bloodRoutineIndicators.findIndex((item) => item.createdAt === this.showBloodRoutineIndicator.createdAt) - 1;
            if (index >= 0) {
                this.showBloodRoutineIndicator = this.bloodRoutineIndicators[index];
                this.updateChart();
            }
        },
        nextRecord() {
            const index = this.bloodRoutineIndicators.findIndex((item) => item.createdAt === this.showBloodRoutineIndicator.createdAt) + 1;
            if (index < this.bloodRoutineIndicators.length) {
                this.showBloodRoutineIndicator = this.bloodRoutineIndicators[index];
                this.updateChart();
            }
        },
        initCharts() {
            this.chartOptions = this.getChartOptions();
            this.chart1 = echarts.init(document.getElementById('chart1'));
            this.updateChart();
        },
        initChart2() {
            this.chart2 = echarts.init(document.getElementById('chart2'));
            const option = {
                title: {
                    text: '诊断结果',
                    subtext: '概率',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'right',
                    data: Object.keys(this.probability)
                },
                series: [
                    {
                        name: '概率',
                        type: 'pie',
                        radius: '50%',
                        data: Object.keys(this.probability).map((key, index) => {
                            return {
                                value: this.probability[key],
                                name: key,
                                itemStyle: {
                                    color: [
                                        '#ff6e76', // 第一个元素颜色
                                        '#7cffb2', // 第二个元素颜色
                                        '#fddd60' // 第三个元素颜色
                                    ][index]
                                }
                            };
                        })
                    }
                ]
            };
            this.chart2.setOption(option);
        },
        outRecord() {
            this.$store.record.bloodDrooping = [];
            this.$store.record.probability = {};
            this.$store.record.imgDetail = [];
            this.$store.record.isShow = false;
            this.$store.record.isUpdate = false;
            this.$store.record.text = '';
        },
        newRecord() {
            this.$store.record.clearRecordInfo();
            this.$emit('newRecord');
        },
        async save() {
            const recordId = this.$store.record.recordId;
            const patientId = this.$store.record.patientId;
            const bloodDrooping = this.$store.record.bloodDrooping.history.filter((item) => item.recordId === recordId)[0];
            const uploadBloodDrooping ={... bloodDrooping};
            uploadBloodDrooping['RDW'] =uploadBloodDrooping['RDW-SD'];
            delete uploadBloodDrooping['RDW-SD'];
            const imgDetail = this.$store.record.imgDetail.map((item) => ({
                total: item.total,
                originalImageUrl: item.originalImageUrl,
                details: item.details
            }));
            const probability = this.$store.record.probability;
            const list = {
                recordId,
                patientId,
                bloodDrooping: uploadBloodDrooping,
                imgDetail,
                probability
            };
            if (this.$store.record.txt !== null) {
                this.text = this.$store.record.txt;
            }
            this.saveLoading = true;
            const res = await this.$api.record.saveRecord(list);
            this.saveLoading = false;
            if (res.success) {
                this.$store.record.isUpdate = true;
                this.$api.notify.success('保存成功');
            } else {
                this.$api.notify.error(res.error);
            }
        }
    }
};
</script>
